package org.teachertools.services;

import java.util.List;

import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.teachertools.common.ValidationUtils;
import org.teachertools.data.Eleve;
import org.teachertools.services.exception.ServiceException;

@Repository
@Transactional
public class EleveService extends GenericService<Eleve> {

	@SuppressWarnings("unchecked")
	public List<String> getDistinctClassName() throws ServiceException {
		try
		{
			String request = "select distinct classe from Eleve order by classe";
			return entityManager.createQuery(request).getResultList();
		}
		catch (PersistenceException e)
		{
			logger.error(e.getCause(), e);
			throw new ServiceException(e, "error.db.param", new String[] { e.getCause().getMessage() });
		}
	}

	@Override
	protected Class<Eleve> getObjectClass() {
		return Eleve.class;
	}

	@SuppressWarnings("unchecked")
	public List<Eleve> getEleveForClasse(String classe) throws ServiceException {
		try {
			String request = "from Eleve where classe = :label_1 order by nom";
			Query query = entityManager.createQuery(request);
			query.setParameter("label_1", classe);
			return (List<Eleve>) query.getResultList();
		} catch (PersistenceException e) {
			logger.error(e.getCause(), e);
			throw new ServiceException(e, "error.db.param", new String[] { e.getCause().getMessage() });
		}
	}

	@Override
	protected Query getSearchQuery(Eleve obj) {
		StringBuffer request = new StringBuffer();
		request.append("from Eleve entity where 1 = 1");
		if (ValidationUtils.isNotEmpty(obj.getPrenom())) {
			request.append(" and upper(entity.prenom) like upper(:label_1)");
		}
		if (ValidationUtils.isNotEmpty(obj.getNom())) {
			request.append(" and upper(entity.nom) like upper(:label_2)");
		}
		if (ValidationUtils.isNotEmpty(obj.getClasse())) {
			request.append(" and upper(entity.classe) like upper(:label_3)");
		}
		Query query = entityManager.createQuery(request.toString());
		if (ValidationUtils.isNotEmpty(obj.getPrenom())) {
			query.setParameter("label_1", prepareQueryParam(obj.getPrenom()));
		}
		if (ValidationUtils.isNotEmpty(obj.getNom())) {
			query.setParameter("label_2", prepareQueryParam(obj.getNom()));
		}
		if (ValidationUtils.isNotEmpty(obj.getClasse())) {
			query.setParameter("label_3", prepareQueryParam(obj.getClasse()));
		}
		return query;
	}
}
